import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Like, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Food, NutrientType } from '../entities';

import {
  CreateFoodReqDto,
  FoodListReqDto,
  FoodResDto,
  UpdateFoodDto,
} from './dto/food.dto';
import { CategoryService } from '../category/category.service';
@Injectable()
export class FoodService {
  constructor(
    @InjectRepository(Food)
    private readonly foodsRepository: Repository<Food>,
    private readonly categoryService: CategoryService,
  ) {}

  private async isFoodOrCategoryExist(foodName: string, categoryId: number) {
    const result = {
      hasFood: false,
      hasCategory: false,
    };
    if (!foodName) return result;
    const findFood = await this.foodsRepository.findOne({
      where: { name: foodName, isDeleted: false },
    });
    if (findFood) result.hasFood = true;
    const category = await this.categoryService.findOne({
      categoryId,
    });
    if (category) result.hasCategory = true;
    return result;
  }

  async create(food: CreateFoodReqDto) {
    const { hasFood, hasCategory } = await this.isFoodOrCategoryExist(
      food.name,
      food.categoryId,
    );

    if (hasFood) {
      throw new HttpException('食物已存在', HttpStatus.BAD_REQUEST);
    }
    if (!hasCategory) {
      throw new HttpException('分类不存在', HttpStatus.BAD_REQUEST);
    }

    const newFood = this.foodsRepository.create(food);
    return await this.foodsRepository.save(newFood);
  }

  findAll(params: FoodListReqDto) {
    return this.foodsRepository.find({
      where: {
        isDeleted: false,
        categoryId: params.categoryId,
        tag: Like(`%${params.tag || ''}%`),
      },
      order: { createdAt: 'DESC' },
    });
  }
  async findPage(query: FoodListReqDto): Promise<FoodResDto> {
    const pageNo = query.pageNo || 1;
    const pageSize = query.pageSize || 10;

    const tag = query.tag || '';

    const [list, total] = await this.foodsRepository.findAndCount({
      where: {
        isDeleted: false,
        categoryId: query.categoryId,
        tag: Like(`%${tag}%`),
      },
      relations: ['category'],
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
      order: { createdAt: 'DESC' },
    });

    return { list, total };
  }

  findOne(foodId: number) {
    return this.foodsRepository.findOne({
      where: { foodId, isDeleted: false },
    });
  }

  async update(foodId: string, food: UpdateFoodDto) {
    const { hasFood, hasCategory } = await this.isFoodOrCategoryExist(
      food.name,
      food.categoryId,
    );

    if (!hasFood) {
      throw new HttpException('食物不存在', HttpStatus.BAD_REQUEST);
    }
    if (!hasCategory) {
      throw new HttpException('分类不存在', HttpStatus.BAD_REQUEST);
    }

    return this.foodsRepository.update(foodId, food);
  }

  async fakeRemove(foodId: number) {
    const findFood = await this.foodsRepository.findOne({
      where: { foodId, isDeleted: false },
    });
    if (!findFood) {
      throw new HttpException('食物不存在', HttpStatus.BAD_REQUEST);
    }

    findFood.isDeleted = true;
    return this.foodsRepository.save(findFood);
  }
}
